const { storage } = require("@/lib/storage");

let urlHistoryMap = null;

chrome.contextMenus.removeAll(() => {
    chrome.contextMenus.create({
        title: '添加到主页',
        id: 'addToHome',
        contexts: ['all'],
        type: "normal"
    });
});

// 监听右键菜单被点击事件
chrome.contextMenus.onClicked.addListener((menuInfo, tabInfo) => {
    if (menuInfo.menuItemId === 'addToHome') {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs.length > 0) {
                onAddToHome(tabs[0]);
            }
        });
    }
});
// 监听标签页 URL 变化
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (urlHistoryMap != null && changeInfo.status && changeInfo.status === "complete" && tab.url.startsWith('http') && tab.favIconUrl) {
        let url = tab.url;
        if (url.startsWith('https://')) {
            url = url.substring(8);
        } else if (url.startsWith('http://')) {
            url = url.substring(7);
        }
        url = url.split("/")[0];
        if (!urlHistoryMap[url]) {
            urlHistoryMap[url] = {
                appUrl: tab.favIconUrl,
                url: tab.url,
                key: url,
                title: tab.title,
                time: Date.now(),
                count: 1
            }
        } else {
            urlHistoryMap[url].count = urlHistoryMap[url].count + 1;
            urlHistoryMap[url].url = tab.url;
            urlHistoryMap[url].title = tab.title;
            urlHistoryMap[url].time = Date.now();
            if (tab.favIconUrl) {
                urlHistoryMap[url].appUrl = tab.favIconUrl;
            }
        }
        // 在这里可以处理 URL 变化的逻辑
        saveUrlHistory();
    }
});

function findAvailablePosition(layouts, width, height, maxWidth, maxHeight) {
    for (let y = 0; y < maxHeight; y++) {
        for (let x = 0; x < maxWidth; x++) {
            // 检查当前位置是否与现有组件重叠
            const isOverlapping = layouts.some(layout => {
                return (
                    x < layout.x + layout.w &&
                    x + width > layout.x &&
                    y < layout.y + layout.h &&
                    y + height > layout.y
                );
            });
            if (!isOverlapping) {
                return { x, y };
            }
        }
    }
    return null; // 如果找不到可用位置
}

function onAddToHome(tab) {
    chrome.storage.local.get(['layout', 'layoutSize']).then((data) => {
        const layouts = data.layout ? JSON.parse(data.layout) : [];
        const layoutSize = data.layoutSize ? JSON.parse(data.layoutSize) : { w: 0, h: 0 };

        if (!layouts || layoutSize.w === 0 || layoutSize.h === 0) {
            chrome.notifications.create({
                type: 'basic',
                iconUrl: '/assets/icon/128.png',
                title: 'Awork 提示',
                message: 'Awork未初始化，请先打开首页初始化Awork'
            });
            return;
        }


        // 找到一个可用的位置
        const position = findAvailablePosition(layouts, 2, 2, layoutSize.w, layoutSize.h);
        if (!position) {
            chrome.notifications.create({
                type: 'basic',
                iconUrl: '/assets/icon/128.png',
                title: 'Awork 提示',
                message: '没有可用空间添加组件'
            });
            return;
        }

        layouts.push({
            i: Date.now(),
            x: position.x,
            y: position.y,
            w: 2,
            h: 2,
            static: false,
            system: false,
            component: 'app',
            appUrl: tab.favIconUrl ? tab.favIconUrl : '/assets/app-logo/app.svg',
            url: tab.url,
            title: tab.title,
            isResizable: false
        });

        chrome.storage.local.set({
            'layout': JSON.stringify(layouts)
        });
        chrome.notifications.create({
            type: 'basic',
            iconUrl: '/assets/icon/128.png',
            title: 'Awork 提示',
            message: '快捷方式已添加'
        });
    });
}


/// 获取访问历史
storage.get('urlHistory').then((data) => {
    if (!data) {
        return;
    }
    let us = []
    let map = data ? JSON.parse(data) : {};
    for (let key in map) {
        us.push(map[key])
    }
    us.sort((a, b) => {
        if (b.count === a.count) {
            return b.time - a.time; // 按 time 降序
        }
        return b.count - a.count; // 按 count 降序
    })
    if (us.length > 30) {
        us.splice(30)
    }
    let uMap = {};
    us.forEach((history) => {
        uMap[history.key] = {
            appUrl: history.appUrl,
            url: history.url,
            title: history.title,
            time: history.time,
            key: history.key,
            count: history.count
        }
    });
    urlHistoryMap = uMap;
});

function saveUrlHistory() {
    storage.set('urlHistory', JSON.stringify(urlHistoryMap));
}


/// 
const axios = require('axios'); // 需确保background支持axios或fetch

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === "createTab" && message.url) {
        chrome.tabs.create({ url: message.url });
    }
    // 新增：抓取新闻页面
    if (message.action === "fetchAwyNews") {
        axios.get('https://www.ava.com.cn/news_1.html').then(res => {
            sendResponse({ html: res.data });
        }).catch(err => {
            sendResponse({ error: err.toString() });
        });
        // 必须返回true以支持异步
        return true;
    }
});
